package com.yjymm.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjymm.edu.common.*;
import com.yjymm.edu.config.AdminProperties;
import com.yjymm.edu.exception.AdminLoginException;
import com.yjymm.edu.exception.MyException;
import com.yjymm.edu.mapper.UserMapper;
import com.yjymm.edu.model.common.RoleEnum;
import com.yjymm.edu.model.dto.AdminLoginDTO;
import com.yjymm.edu.model.dto.AdminSearchDTO;
import com.yjymm.edu.model.dto.AdminUpdateDTO;
import com.yjymm.edu.model.entity.User;
import com.yjymm.edu.model.vo.AdminLoginVo;
import com.yjymm.edu.service.AdminService;
import lombok.ToString;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.management.Query;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yjymm
 * @date 2021-03-21 1:59
 */
@Service
public class AdminServiceImpl implements AdminService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private AdminProperties adminProperties;

    @Resource
    private JwtConfigProperties jwtConfigProperties;

    /**
     * 管理员登陆
     *
     * @param dto
     * @return
     */
    @Override
    public AdminLoginVo adminLogin(AdminLoginDTO dto) throws Exception {

        User user = userMapper.selectAdmin(dto.getUsername(), dto.getPassword());
        if (user == null) {
            throw new AdminLoginException("账号名或密码不正确");
        }
        if (user.getDeleted() == 1) {
            throw new AdminLoginException("此账号已被禁用");
        }
        File file = ResourceUtils.getFile(jwtConfigProperties.getPrivateKeyPath());
        String token = JwtUtils.generateTokenExpireInMinutes(dto, RsaUtils.getPrivateKeyByFile(file), jwtConfigProperties.getExpireMinutes());
        AdminLoginVo adminLoginVo = new AdminLoginVo(token, jwtConfigProperties.getExpireMinutes());
        adminLoginVo.setUser(user);
        return adminLoginVo;

//        if (adminProperties.getPassword().equals(dto.getPassword())
//                && adminProperties.getUsername().equals(dto.getUsername())) {
//            // 生成token返回
//            File file = ResourceUtils.getFile(jwtConfigProperties.getPrivateKeyPath());
//            String token = JwtUtils.generateTokenExpireInMinutes(dto, RsaUtils.getPrivateKeyByFile(file), jwtConfigProperties.getExpireMinutes());
//            AdminLoginVo adminLoginVo = new AdminLoginVo(token, jwtConfigProperties.getExpireMinutes());
//            return adminLoginVo;
//        }
//        throw new AdminLoginException("登陆名或密码不正确");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertAdmin(AdminLoginDTO dto) {
        User user = MyBeanUtils.copyProperties2Object(dto, User.class);
        Map<String,Object> map = new HashMap<>();
        map.put("username",dto.getUsername());
        map.put("role_id",RoleEnum.ADMIN.getId());
        map.put("deleted",0);
        List<User> users = userMapper.selectByMap(map);
        if (!CollectionUtils.isEmpty(users)){
            throw new MyException("该管理员已存在，请重新添加");
        }
        user.setRoleId(RoleEnum.ADMIN.getId());
        user.setOpenId(StringUtils.getRandomString("admin-"));
        userMapper.insert(user);
    }

    @Override
    public IPage list(AdminSearchDTO dto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", RoleEnum.ADMIN.getId());
//        .eq("deleted",0);
        if (!StringUtils.isBlank(dto.getUsername())) {
            queryWrapper.like("username",dto.getUsername());
        }
        IPage<User> page = userMapper.selectPage(new Page<>(dto.getPage(), dto.getSize()), queryWrapper);
        return page;
    }

    /**
     * 更新管理员密码
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePass(AdminUpdateDTO dto) {
        User user = userMapper.selectById(dto.getId());
        user.setPassword(dto.getPassword());
        userMapper.updateById(user);
    }

    /**
     * 启用禁用管理员账号
     * @param adminId
     * @param code
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void statusOpt(Integer adminId, Integer code) {
        User user = userMapper.selectById(adminId);
        if (user == null) {
            throw new MyException("记录不存在");
        }
        if (user.getRoleId() != RoleEnum.ADMIN.getId()) {
            throw new MyException("此账号不是管理员账号");
        }
        if (code == 1) {
            // 启用
            user.setDeleted(0);
        } else if (code == 2) {
            // 禁用
            user.setDeleted(1);
        }
        userMapper.updateById(user);
    }
}
